package com.douwong.student.socket;

import android.util.Log;

import com.douwong.student.utils.JsonUtils;
import com.douwong.student.utils.TypeConvertUtils;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import java.nio.charset.Charset;

public class TcpCodeFilter implements ProtocolCodecFactory {
	private static final String TAG =TcpCodeFilter.class.getSimpleName() ;
	private short ffe=0xff;
	// 解码
	@Override
	public ProtocolDecoder getDecoder(IoSession arg0) throws Exception {
		CumulativeProtocolDecoder decoder = new CumulativeProtocolDecoder() {
			@Override
			protected boolean doDecode(IoSession session, IoBuffer in,
									   ProtocolDecoderOutput out) throws Exception {
				Log.i(TAG,"位置　：　"+in.position()+"限制 ： "+in.limit()+"容量  : "+in.capacity());
				if (in.remaining() < 4) {
					return false;
				}
				in.mark();//positon置0
			//	in.position(11);
				//取包头
				byte [] byteffes=new byte[4];
				in.get(byteffes, 0, byteffes.length);
				int  pack = TypeConvertUtils.toInt(byteffes);
				int effs=pack;
				int eff = effs >> 22;
				//判断包头
				if (eff==ffe){
					//int a=pack^(ffe<<22);
					int newPack=((pack<<10)>>>10);
					Log.i(TAG,"数据的长度"+newPack);
					///	int length = Integer.parseInt(in.getString(4, Charset.forName("UTF-8").newDecoder()));
					//in.remaining,返回当前位置与限制之间的元素数。
					if (newPack > in.remaining()) {//如果消息内容不够，则重置，相当于不读取size
						//把当前位置设置为标记的值
						in.reset();
						return false;
					}
					byte[] bytes = new byte[newPack];
					in.get(bytes, 0, newPack);
					if (bytes.length==1){
						out.write(bytes);
					}else {
						String json = new String(bytes, "UTF-8");
						out.write(json);
					}

				}else {
					return false;
				}

				if (in.remaining() > 0) {
					return true;
				} else {
					return false;
				}
			}
		};
		return decoder;
	}

	// 编码
	@Override
	public ProtocolEncoder getEncoder(IoSession arg0) throws Exception {
		ProtocolEncoder encoder = new ProtocolEncoder() {
			@Override
			public void encode(IoSession session, Object message,
							   ProtocolEncoderOutput out) throws Exception {
				byte [] byteJson;
				if (message instanceof byte[]){
					 byteJson= (byte[]) message;
				}else {
					String json=	JsonUtils.serialize(message);
					 byteJson = json.getBytes(Charset.forName("UTF-8"));//编码
				}

				int jsle=	(ffe<<22)|byteJson.length;
				byte[] intToByteArray = TypeConvertUtils.toBytes(jsle);
				IoBuffer buffer = IoBuffer.allocate(byteJson.length
						+ intToByteArray.length);
				Log.i(TAG,"容量"+byteJson.length
						+ intToByteArray.length);
				buffer.put(intToByteArray);
				buffer.put(byteJson);
				buffer.flip();
				out.write(buffer);
			}

			@Override
			public void dispose(IoSession session) throws Exception {
				// TODO Auto-generated method stub

			}
		};
		return encoder;
	}




}
